package com.miracle9.game.service;

import com.miracle9.game.bean.Pager;
import com.miracle9.game.dao.*;
import com.miracle9.game.entity.*;
import com.miracle9.game.server.message.AmfMessageSend;
import com.miracle9.game.util.MyUtil;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("payLogService")
public class PayLogService
        extends BaseService {

    @Autowired
    private PayLogServiceDao payLogServiceDao;
    @Autowired
    private PayApplyServiceDao payApplyServiceDao;
    @Autowired
    private UserServiceDao userServiceDao;
    @Autowired
    private UserService userService;
    @Autowired
    private SystemConfigServiceDao systemConfigServiceDao;
    @Autowired
    private UserWarningServiceDao userWarningServiceDao;
    @Autowired
    private UserWarningBakServiceDao userWarningBakServiceDao;

    public Map<String, Object> getUserPayLog(int userId, String startDate, String endDate, Pager pager, IoSession session) {
        Map map = new HashMap();
        double lastTotalMoney = 0.0D;
        endDate = MyUtil.DateByDayCalendar(endDate, 1);
        if ((pager.getOrder() == "") && (pager.getOrderBy() == "")) {
            pager.setOrderBy("datetime");
            pager.setOrder("desc");
        }
        pager = this.payLogServiceDao.q_CreateSqlsPager("from PayLog where userId=? and datetime>=? and datetime<=? and type=0 and userType=0", pager, new Object[]{Integer.valueOf(userId), startDate, endDate});
        List datas = new ArrayList();
        for (Object o : pager.getList()) {
            PayLog payLog = (PayLog) o;
            Map data = new HashMap();
            data.put("datetime", payLog.getDatetime());
            data.put("username", payLog.getUsername());
            data.put("money", Double.valueOf(payLog.getMoney()));
            data.put("admin", payLog.getAdmin());
            data.put("gameGold", Integer.valueOf(payLog.getGameGold()));
            if (payLog.getExpiryType() == 0) {
                data.put("expiryType", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "zhuDongFaQi"));
            } else {
                data.put("expiryType", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "wanJiaFaQi"));
            }
            data.put("remark", payLog.getRemark());
            datas.add(data);
        }
        pager.setList(datas.toArray());
        map.put("pager", pager);
        String hql1 = "select ifnull(sum(money),0) from pay_log where user_id=" + userId + " and datetime>=? and datetime<=? and type=0 and user_type=0 ";

        List log = this.userServiceDao.returnList_3(hql1, startDate, endDate);
        for (Object o1 : (List) log) {
            lastTotalMoney += Double.parseDouble(o1.toString());
        }
        map.put("lastTotalMoney", Double.valueOf(lastTotalMoney));
        return map;
    }

    public Map<String, Object> getUserExchangeLog(int userId, String startDate, String endDate, Pager pager, IoSession session) {
        Map map = new HashMap();
        double lastTotalMoney = 0.0D;
        endDate = MyUtil.DateByDayCalendar(endDate, 1);
        if ((pager.getOrder() == "") && (pager.getOrderBy() == "")) {
            pager.setOrderBy("datetime");
            pager.setOrder("desc");
        }
        pager = this.payLogServiceDao.q_CreateSqlsPager(
                "from PayLog where userId=? and datetime>=? and datetime<=? and type=1 and userType=0", pager, new Object[]{Integer.valueOf(userId),
                        startDate, endDate});
        List datas = new ArrayList();
        for (Object o : pager.getList()) {
            PayLog payLog = (PayLog) o;
            Map data = new HashMap();
            data.put("datetime", payLog.getDatetime());
            data.put("username", payLog.getUsername());
            data.put("money", Double.valueOf(payLog.getMoney()));
            data.put("admin", payLog.getAdmin());
            data.put("gameGold", Integer.valueOf(payLog.getGameGold()));
            if (payLog.getExpiryType() == 0) {
                data.put("expiryType", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "zhuDongFaQi"));
            } else {
                data.put("expiryType", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "wanJiaFaQi"));
            }
            data.put("remark", payLog.getRemark());
            datas.add(data);
        }
        pager.setList(datas.toArray());
        map.put("pager", pager);
        String hql1 = "select ifnull(sum(money),0) from pay_log where user_id=" + userId + " and datetime>=? and datetime<=? and type=1 and user_type=0 ";

        List log = this.userServiceDao.returnList_3(hql1, startDate, endDate);
        for (Object o1 : (List) log) {
            lastTotalMoney = Double.parseDouble(o1.toString());
        }
        map.put("lastTotalMoney", Double.valueOf(lastTotalMoney));
        return map;
    }

    public List<PayLog> getPayLog(String startDate, String endDate) {
        return this.payLogServiceDao.q_CreateSqlList("from PayLog where type=0 and datetime>=? and datetime<?", new Object[]{startDate, endDate});
    }

    public Map<String, Object> getUserExpiry(int userId, IoSession session) {
        Map result = new HashMap();
        PayApply log = this.payApplyServiceDao.getByuserIdAndUserType_0(userId, 1);
        System.out.println("getUserExpiry:" + log);
        if (log == null) {
            result.put("success", Boolean.valueOf(false));
            result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "expiryTimeout"));
            return result;
        }
        result.put("success", Boolean.valueOf(true));
        result.put("message", "");
        result.put("remark", log.getRemark());
        result.put("gold", Integer.valueOf(log.getAmmount()));
        System.out.println("getUserExpiry:" + result);
        return result;
    }

    public Map<String, Object> checkUserWarning(int nUserId, int nExpiryCount, IoSession session) {
        Map result = new HashMap();

        result = checkWarning(nUserId, nExpiryCount);

        return result;
    }

    public Map<String, Object> cancelUserExpiry(int userId, IoSession session) {
        Map result = new HashMap();
        IoSession hallSession;
        synchronized (PayApplyService.expiryLock) {
            PayApply log = this.payApplyServiceDao.getByuserIdAndUserType_0(userId, 1);
            if (log == null) {
                User user = (User) this.userServiceDao.getById(Integer.valueOf(userId));
                result.put("success", Boolean.valueOf(true));
                result.put("newGold", Integer.valueOf(user.getGameGold()));
                result.put("message", "");
                return result;
            }
            this.userServiceDao.updateGameById(Integer.valueOf(userId), log.getAmmount(), 0);
            this.userServiceDao.updateExpiryNum(userId, 0);
            log.setState(PayApply.PayApplyState.WAIVE);

            List<PayApply> logs = this.payApplyServiceDao.getAllPayApply();
            for (PayApply ul : logs) {
                if (ul.getId() == log.getId()) {
                    logs.remove(ul);
                    break;
                }
            }
            hallSession = (IoSession) com.miracle9.game.util.GameParameterAssist.ba.get(Integer.valueOf(userId));
            if (hallSession != null) {
                log.setNotice(true);
                UserService.excharge(hallSession);
            }
            this.payApplyServiceDao.update(log);
        }
        List<PayApply> logs;
        Map countMap = userService.getUserPayCount();
        for (IoSession as : com.miracle9.game.util.GameParameterAssist.be.values()) {
            AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(as, "userPayCount", new Object[]{countMap}));
        }
        User user = (User) this.userServiceDao.getById(Integer.valueOf(userId));

        UserService.pubGoldNotice(user);

        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        double userMoney = MyUtil.goldExchange(user.getGameGold(), config.getPayScale());
        if ((config.getMoneyOverrun() != -1) && (userMoney >= config.getMoneyOverrun()) && (user.getOverflow() == 0)) {
            this.userServiceDao.updateOverflow(userId, 1);
            UserService.pubOverflowNotice(userId);
        }
        result.put("success", Boolean.valueOf(true));
        result.put("newGold", Integer.valueOf(user.getGameGold()));
        result.put("message", "");
        return result;
    }

    public Map<String, Object> getUserMinus(int userId, String startDate, String endDate, Pager pager, IoSession session) {
        Map map = new HashMap();
        long lastTotalGold = 0L;
        endDate = MyUtil.DateByDayCalendar(endDate, 1);
        User user = (User) this.userServiceDao.getById(Integer.valueOf(userId));
        if ((pager.getOrder() == "") && (pager.getOrderBy() == "")) {
            pager.setOrderBy("datetime");
            pager.setOrder("desc");
        }
        pager = this.payLogServiceDao.q_CreateSqlsPager("from PayLog where username=? and datetime>=? and datetime<=? and type=2",
                pager, new Object[]{user.getUsername(), startDate, endDate});
        List datas = new ArrayList();
        for (Object o : pager.getList()) {
            PayLog payLog = (PayLog) o;
            Map data = new HashMap();
            data.put("datetime", payLog.getDatetime());
            data.put("username", user.getUsername());
            data.put("gold", Integer.valueOf(payLog.getGold()));
            data.put("admin", payLog.getAdmin());
            datas.add(data);
        }
        pager.setList(datas.toArray());
        map.put("pager", pager);

        String hql1 = "select ifnull(sum(gold),0) from pay_log where username=? and datetime>=? and datetime<=? and type=2 ";

        List log = this.userServiceDao.returnList_4(hql1, user.getUsername(), startDate, endDate);
        for (Object o1 : (List) log) {
            lastTotalGold = Long.parseLong(o1.toString());
        }
        map.put("lastTotalGold", Long.valueOf(lastTotalGold));
        return map;
    }

    public Map<String, Object> getUserPay(int userId, IoSession session) {
        Map result = new HashMap();
        PayApply log = this.payApplyServiceDao.getByuserIdAndUserType_0(userId, 0);
        if (log == null) {
            result.put("success", Boolean.valueOf(false));
            result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "payTimeout"));
            return result;
        }
        result.put("success", Boolean.valueOf(true));
        result.put("message", "");
        result.put("remark", log.getRemark());
        result.put("money", Integer.valueOf(log.getAmmount()));
        return result;
    }

    public Map<String, Object> cancelUserPay(int userId, IoSession session) {
        Map result = new HashMap();
        IoSession hallSession;
        synchronized (PayApplyService.expiryLock) {
            PayApply log = this.payApplyServiceDao.getByuserIdAndUserType_0(userId, 0);
            if (log == null) {
                result.put("success", Boolean.valueOf(false));
                result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "payTimeout"));
                return result;
            }
            this.userServiceDao.updatePayMoney(userId, 0);
            log.setState(PayApply.PayApplyState.WAIVE);
            List<PayApply> logs = this.payApplyServiceDao.getAllPayApply();
            for (PayApply ul : logs) {
                if (ul.getId() == log.getId()) {
                    logs.remove(ul);
                    break;
                }
            }
            hallSession = (IoSession) com.miracle9.game.util.GameParameterAssist.ba.get(Integer.valueOf(userId));
            if (hallSession != null) {
                log.setNotice(true);
                UserService.recharge(hallSession);
            }
            this.payApplyServiceDao.update(log);
        }
        List<PayApply> logs;
        Map countMap = userService.getUserPayCount();
        for (IoSession as : com.miracle9.game.util.GameParameterAssist.be.values()) {
            AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(as, "userPayCount", new Object[]{countMap}));
        }
        result.put("success", Boolean.valueOf(true));
        result.put("message", "");
        return result;
    }

    public Map<String, Object> checkWarning(int userId, int expiryCount) {
        UserWarning userWarning = new UserWarning();
        userWarning = (UserWarning) this.userWarningServiceDao.q_CreateSqlFilter("from UserWarning where userId=? ", new Object[]{Integer.valueOf(userId)});

        UserWarningBak userWarningBak = new UserWarningBak();
        userWarningBak = (UserWarningBak) this.userWarningBakServiceDao.q_CreateSqlFilter("from UserWarningBak where userId=? ", new Object[]{Integer.valueOf(userId)});

        SystemConfig systemConfig = new SystemConfig();

        int payScale = (int) MyUtil.doubleDivideCalculation(Double.valueOf(systemConfig.getPayScale()).doubleValue(), 100.0D);

        long expiyNum = expiryCount;

        long lExpiryCount = userWarning.getExpiryCount() - userWarningBak.getExpiryCount() + expiyNum;
        long lPayCount = userWarning.getPayCount() - userWarningBak.getPayCount();
        long lGameGold = userWarning.getGameGold() - userWarningBak.getGameGold() - expiyNum;
        long lDeductGold = userWarning.getDeductGold() - userWarningBak.getDeductGold();
        long lGiveGold = userWarning.getGiveGold() - userWarningBak.getGiveGold();
        long lDeGold = (long) (userWarning.getDeGold() - userWarningBak.getDeGold());
        long lYaGold = (long) (userWarning.getYaGold() - userWarningBak.getYaGold());

        long lLeft = lExpiryCount - lPayCount + lGameGold + lDeductGold - lGiveGold;

        long lRight = lDeGold - lYaGold + 500L;

        Map warningResult = new HashMap();
        long division;
        if ((lExpiryCount == 0L) || (payScale == 0)) {
            division = 0L;
        } else {
            division = lExpiryCount / payScale;
        }
        if (lLeft > lRight) {
            warningResult.put("status", Integer.valueOf(1));
            warningResult.put("expiryGold", Long.valueOf(lLeft - lRight));
            com.miracle9.game.util.GameParameterAssist.aJ.add(Integer.valueOf(userId));

            this.userServiceDao.updateWarningStatus(userId, (int) (lLeft - lRight));

            this.userServiceDao.updateStatus(userId, 1);
        } else if ((division > 50000L) && (lExpiryCount + lGameGold > 10L * lPayCount + 100L)) {
            warningResult.put("status", Integer.valueOf(2));
            warningResult.put("expiryGold", Long.valueOf(userWarning.getExpiryCount()));
            warningResult.put("payGold", Long.valueOf(userWarning.getPayCount()));
            warningResult.put("yaGold", Double.valueOf(userWarning.getYaGold()));
            warningResult.put("deGold", Double.valueOf(userWarning.getDeGold()));
            com.miracle9.game.util.GameParameterAssist.aJ.add(Integer.valueOf(userId));

            this.userServiceDao.updateWarningStatus(userId, -1);

            this.userServiceDao.updateStatus(userId, 1);
        } else if ((division > 100000L) && (lExpiryCount + lGameGold > 5L * lPayCount + 100L)) {
            warningResult.put("status", Integer.valueOf(2));
            warningResult.put("expiryGold", Long.valueOf(userWarning.getExpiryCount()));
            warningResult.put("payGold", Long.valueOf(userWarning.getPayCount()));
            warningResult.put("yaGold", Double.valueOf(userWarning.getYaGold()));
            warningResult.put("deGold", Double.valueOf(userWarning.getDeGold()));
            com.miracle9.game.util.GameParameterAssist.aJ.add(Integer.valueOf(userId));
            this.userServiceDao.updateWarningStatus(userId, -1);

            this.userServiceDao.updateStatus(userId, 1);
        } else {
            warningResult.put("status", Integer.valueOf(-1));
        }
        return warningResult;
    }

    public void deletePastPayLog(String date) {
        this.payLogServiceDao.deleteByDate(date);
    }

}
